<template>
  <div class="app-container">
    <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <div style="display: inline-block;width: 300px;" v-if="this.$route.query.id==null">
          <el-form-item label="采购订单" prop="">
            <input type="text" v-model="this.orderId" readonly @click="selectOrder" style="padding: 7px;border-radius: 5px;border: 1px gainsboro solid;width: 180px" placeholder=" 请选择采购订单"/>
          </el-form-item>
        </div>
        <div style="display: inline-block;width: 300px;">
          <el-form-item label="仓库" prop="scName">
            <el-select v-model="form.scId" placeholder="" clearable :style="{width: '100%'}" disabled>
              <el-option v-for="(item, index) in StoreCenterInfoList" :key="index" :label="item.name"
                         :value="item.id" >{{item.name}}</el-option>
            </el-select>
          </el-form-item>
        </div>
        <div style="display: inline-block;width: 300px;">
          <el-form-item label="供应商" prop="customerName">
            <el-select v-model="form.supplierId" placeholder="" @keyup.enter.native="handleQuery" disabled>
              <el-option v-for="supplier in SupplierList" :key="supplier.id" :value="supplier.id" :label="supplier.name">{{supplier.name}}</el-option>
            </el-select>
          </el-form-item>
        </div>
        <div style="display: inline-block;width: 300px;">
          <el-form-item label="采购员" prop="purchaserId" >
            <el-select v-model="form.purchaserId" placeholder="" @keyup.enter.native="handleQuery" disabled>
              <el-option v-for="user in UserList" :key="user.userId" :value="user.userId" :label="user.userName">{{user.userName}}</el-option>
            </el-select>
          </el-form-item>
        </div>
        <br>
        <div style="display: inline-block;width: 300px;">
          <el-form-item label="实际到货日期" prop="approveTime">
            <el-date-picker clearable
                            v-model="form.receiveDate"
                            type="date"
                            style="width: 150px"
                            value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </div>
        <br>
        <div style="display: inline-block;width: 300px;" v-if="this.$route.query.id!=null"><p>状态：<span :style="{color: statusColor}">{{ this.form.status==0 ? '待审核' : (this.form.status==3 ? '审核通过' : '审核拒绝') }}</span></p></div>
        <div style="display: inline-block;width: 300px;" v-if="form.status==6"><p>拒绝原因：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 180px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" v-model="form.refuseReason" disabled></p></div>
        <br>
        <div style="display: inline-block;width: 300px;" v-if="this.$route.query.id!=null"><p>操作人：{{ this.form.createBy }}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.$route.query.id!=null"><p>操作时间：{{ this.form.createTime }}</p></div>
      </el-form>
    </div>
    <div style="border: 1px gainsboro solid;margin-top: 5px">
      <el-table height="400px" v-loading="loading" :data="this.tblReceiveSheetDetailList" v-model="this.productList">
        <!--        商品数据-->
        <el-table-column label="商品编号" align="left" prop="baseDataProduct.code" width="200px" v-if="purchaseType===0"/>
        <el-table-column label="商品名称" align="left" prop="baseDataProduct.name" width="200px" v-if="purchaseType===0"/>
        <el-table-column label="单位" align="left" prop="baseDataProduct.unit" width="100px" v-if="purchaseType===0"/>
        <el-table-column label="规格" align="left" prop="baseDataProduct.spec" width="100px" v-if="purchaseType===0"/>
        <el-table-column label="商品类目" align="left" prop="baseDataProduct.baseDataProductCategory.name" width="100px" v-if="purchaseType===0"/>
        <el-table-column label="商品品牌" align="left" prop="baseDataProduct.baseDataProductBrand.name" width="100px" v-if="purchaseType===0"/>

        <!--        物料数据-->
        <el-table-column label="物料编号" align="left" prop="material.materialCode" width="200px" v-if="purchaseType===1"/>
        <el-table-column label="物料名称" align="left" prop="material.materialName" width="150px" v-if="purchaseType===1"/>
        <el-table-column label="物料类型" align="left" prop="material.typeName" width="100px" v-if="purchaseType===1"/>
        <el-table-column label="规格型号" align="left" prop="material.specification" width="150px" v-if="purchaseType===1"/>
        <el-table-column label="分类名称" align="left" prop="material.categoryName" width="100px" v-if="purchaseType===1"/>
        <el-table-column label="单位" align="left" prop="material.purchaseUnitName" width="100px" v-if="purchaseType===1"/>

        <el-table-column label="采购数量" align="left" prop="tblPurchaseOrderDetail.orderNum" width="100px"/>
        <el-table-column label="剩余收货数量" align="left" prop="tblPurchaseOrderDetail.orderNum" width="100px">
          <template slot-scope="scope">
            <span>{{
                scope.row.tblPurchaseOrderDetail.orderNum-scope.row.tblPurchaseOrderDetail.returnNum < scope.row.tblPurchaseOrderDetail.receiveNum ? 0 : scope.row.tblPurchaseOrderDetail.orderNum-scope.row.tblPurchaseOrderDetail.returnNum-scope.row.tblPurchaseOrderDetail.receiveNum
              }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收货数量" align="left" prop="receiveNum" width="150">
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.receiveNum" @input="getSumNumber"
                      :disabled="scope.row.receiveNum==0 && scope.row.tblPurchaseOrderDetail.receiveNum==scope.row.tblPurchaseOrderDetail.orderNum"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left" prop="description" width="200">
          <template slot-scope="scope">
            <input type="text" v-model="scope.row.description" style="padding: 10px;border-radius: 5px;border: 1px gainsboro solid;width: 180px;">
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px;text-align: right">
      <label >备注： </label>
      <textarea v-model="form.description" style="width: 90%;height: 50px;margin-top: 10px;margin-left: 10px;margin-bottom: 10px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid"/>
    </div>

    <div slot="footer" class="dialog-footer" style="text-align: center;margin: 5px">
      <el-button type="primary" @click="submitForm(0)">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>


    <!-- 获取采购订单弹窗 -->
    <el-dialog title="采购订单" :visible.sync="dialogFormVisible" width="1000px">
      <el-form :model="orderQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="单号" prop="code">
          <el-input
            v-model="orderQueryParams.code"
            placeholder="请输入单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库" prop="scId">
          <el-select v-model="orderQueryParams.scId" @keyup.enter.native="handleQuery" clearable>
            <el-option v-for="storeCenter in StoreCenterInfoList" :key="storeCenter.id" :value="storeCenter.id" :label="storeCenter.name">{{storeCenter.name}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId" >
          <el-select v-model="orderQueryParams.supplierId" @keyup.enter.native="handleQuery" clearable>
            <el-option v-for="supplier in SupplierList" :key="supplier.id" :value="supplier.id" :label="supplier.name">{{supplier.name}}</el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="PurchaseOrderList" @row-click="handleRowClick">
        <el-table-column width="55" align="center">
          <template slot-scope="scope">
            <el-radio :label="scope.$index" v-model="selectedRowIndex" @change.native="handleRadioChange(scope.$index)"><span style="display: none">0</span></el-radio>
          </template>
        </el-table-column>
<!--        <el-table-column label="编号" align="left" prop="id" width="200px"/>-->
        <el-table-column label="业务单据号" align="left" prop="code" width="200px"/>
        <el-table-column label="仓库名称" align="left" prop="scName" width="100px"/>
        <el-table-column label="供应商名称" align="left" prop="supplierName" width="100px"/>
        <el-table-column label="采购员" align="left" prop="purchaserName" width="100px"/>
        <el-table-column label="采购金额" align="left" prop="totalAmount" width="100px">
          <template slot-scope="scope">
            <span>{{Number(scope.row.totalAmount).toLocaleString('en-US') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="采购数量" align="left" prop="totalNum" width="100px"/>
        <el-table-column label="预计到货日期" align="left" prop="expectArriveDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expectArriveDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left" prop="description" width="100px"/>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"  @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {parseTime} from "../../../utils/ruoyi";
import { listReceiveSheet, getReceiveSheet, delReceiveSheet, addReceiveSheet, updateReceiveSheet,listByScId } from "@/api/system/ReceiveSheet";
import {listUser} from "@/api/system/user";
import {listSupplier} from "@/api/system/Supplier";
import {listStoreCenterInfo} from "@/api/system/StoreCenterInfo";
import {listProductInfo} from "@/api/system/ProductInfo";
//商品库存
import { listStock} from "@/api/system/stock";
import {listPurchaseOrder} from "@/api/system/PurchaseOrder";
import order from "@/views/system/order/index.vue";
import {listMaterialStock} from "@/api/system/MaterialStock";

export default {
  name: "orderAdd",
  data() {
    const today = new Date().toISOString().slice(0, 10); // 格式：yyyy-MM-dd

    return {
      //订单ID框
      orderId:null,
      // 订单查询参数
      orderQueryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        scId: null,
        supplierId: null,
        purchaserId: null,
        createBy: null,
        createTime: null,
        approveBy: null,
        approveTime: null,
        status: 3,
      },
      //订单数据
      PurchaseOrderList:[],
      selectedRowIndex: -1, // 选中的行索引
      selectedRowData: null, // 选中的行数据

      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 商品数据
      productList: [],

      // 收货数量
      receiveNum: 0,
      //商品数量
      orderNum:0,
      // 赠品数量
      giftNum: 0,
      // 含税总金额
      taxAmount: 0,

      //状态颜色
      statusColor:"rgb(100, 100, 100)",
      //用户列表
      UserList: [],
      // 供应商列表
      SupplierList: [],
      //仓库列表
      StoreCenterInfoList: [],
      // 采购收货明细表格数据
      tblReceiveSheetDetailList: [],
      // 采购收货表格数据
      ReceiveSheetList: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scName: null,
        customerName: null,
      },

      // 表单参数
      form: {
        id:null,
        code:null,
        scId:null,
        scCode:null,
        scName:null,
        supplierId:null,
        supplierCode:null,
        supplierName:null,
        purchaserId:null,
        purchaseName:null,
        expectArriveDate:null,
        totalNum:0,
        totalGiftNum:0,
        totalAmount:0,
        description:"",
        createBy:null,
        createById:null,
        createTime:null,
        updateBy:null,
        updateById:null,
        updateTime:null,
        approveBy:null,
        approveTime:null,
        status:null,
        refuseReason:null,
        remark:null,
        tblOrderPayTypeList:[],
        tblPurchaseOrderDetailList:[],
        receiveDate:today
      },

      // 查询参数
      productQueryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        shortName: null,
        skuCode: null,
        categoryId: null,
        brandId: null,
        productType: null,
        available: null,
        createTime: null,
      },
      //收货表订单ID
      orderIdList:[],
      //收货表ID数据
      ReceiveSheetAllList:[],
      //收货详情表ID数据
      ReceiveSheetDetailAllList:[],
      // 商品库存表格ID数据
      productStockAllList: [],

      // 物料库存表格ID数据
      materialStockAllList: [],

      //订单弹窗
      dialogFormVisible: false,
      orderForm: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '120px',

      //采购类型
      purchaseType:null,
    };
  },
  created() {
    //用户数据
    this.getUserList();
    //供应商数据
    this.getSupplierList();
    //仓库数据
    this.getStoreCenterInfoList();

    //收货数据
    this.getReceiveSheetAllList();
    if (this.$route.query.id!=null){
      this.selectReceiveSheet();
    }
    this.loading = false;
  },
  methods: {
    parseTime,
    /** 查询收货详情 */
    async selectReceiveSheet() {
      const id = this.$route.query.id
      await this.getProductStockList(); // 确保商品库存列表加载完成
      await this.getMaterialStockList();
      try {
        const response = await getReceiveSheet(id);
        this.form = response.data;
        this.form.purchaserId = parseInt(this.form.purchaserId);
        this.purchaseType=response.data.tblReceiveSheetDetailList[0].purchaseType;

        //判断收货单是否为被退货状态
        let info=true;
        for (let i = 0; i < this.form.tblReceiveSheetDetailList.length; i++) {
          if (this.form.tblReceiveSheetDetailList[i].receiveNum!=this.form.tblReceiveSheetDetailList[i].returnNum){
            info=false;
          }

          if (this.purchaseType==0){
            const stock = await this.getProductStock(
              this.form.scId,
              this.form.tblReceiveSheetDetailList[i].productId
            );

            if (stock) {
              this.form.tblReceiveSheetDetailList[i].baseDataProduct.tblProductStock = stock;
            } else {
              this.form.tblReceiveSheetDetailList[i].baseDataProduct.tblProductStock = {
                id: generateUniqueId(this.productStockAllList),
                scId: this.form.scId,
                productId: this.form.tblReceiveSheetDetailList[i].productId,
                stockNum: 0,
                taxPrice: this.form.tblReceiveSheetDetailList[i].taxPrice,
                taxAmount: 0,
              };
            }
          }else {
            const stock = await this.getMaterialStock(
              this.form.scId,
              this.form.tblReceiveSheetDetailList[i].materialId
            );

            if (stock) {
              this.form.tblReceiveSheetDetailList[i].material.materialStock = stock;
            } else {
              this.form.tblReceiveSheetDetailList[i].material.materialStock = {
                id: generateUniqueId(this.materialStockAllList),
                warehouseId: this.form[i].scId,
                materialId: this.form.tblReceiveSheetDetailList[i].materialId,
                materialCode: this.form.tblReceiveSheetDetailList[i].material.materialCode,
                materialName: this.form.tblReceiveSheetDetailList[i].material.materialName,
                stockQuantity: 0,
              };
            }
          }
        }

        if (info){
          this.$confirm('该收货单的所有货物被暂定为退货状态，暂时无法修改...', '提示', {
            confirmButtonText: '确定',
            showCancelButton: false, // 隐藏取消按钮
            type: 'warning'
          }).then(() => {
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back(); // 点击确定后返回上一页
          }).catch(() => {
            // 用户点击遮罩层等操作时可能会触发这里，可选处理
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back(); // 点击确定后返回上一页
          });
        }

        if (this.purchaseType==1){
          for (let i = 0; i < this.form.tblReceiveSheetDetailList.length; i++) {
            let num=this.form.tblReceiveSheetDetailList[i].material.materialType
            let name= num===1 ? "原材料" : num===2 ? "半成品" :num===3 ? "成品" : "辅料"
            this.form.tblReceiveSheetDetailList[i].material.typeName=name
          }
        }
        this.tblReceiveSheetDetailList = this.form.tblReceiveSheetDetailList;

        //状态值颜色判断
        if (response.data.status == 0){
          this.statusColor = "rgb(100, 100, 100)";
        }else if (response.data.status==3){
          this.statusColor = "rgb(82, 196, 26)";
        }else {
          this.statusColor = "rgb(255, 0, 0)";
        }

        this.tblReceiveSheetDetailList.forEach(row => {
          row.sumPrice = row.tblPurchaseOrderDetail.taxPrice * row.tblPurchaseOrderDetail.orderNum;
        });

        this.getSumNumber();

      } catch (error) {
        console.error('获取采购收货列表失败:', error);
      } finally {
        this.loading = false;
      }
    },

    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.UserList = response.rows;
      });
    },
    /** 查询供应商列表 */
    getSupplierList() {
      this.loading = true;
      listSupplier(this.queryParams).then(response => {
        this.SupplierList = response.rows;
      });
    },
    /** 查询仓库列表 */
    getStoreCenterInfoList() {
      this.loading = true;
      listStoreCenterInfo(this.queryParams).then(response => {
        this.StoreCenterInfoList = response.rows;
      });
    },


    //订单点击事件
    selectOrder() {
      this.dialogFormVisible=true;
      this.getOrderList();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.orderQueryParams.pageNum = 1;
      this.getOrderList();
    },
    /** 查询采购订单列表 */
    async getOrderList() {
      this.loading = true;
      this.PurchaseOrderList = [];

      await this.getProductStockList(); // 确保商品库存列表加载完成
      await this.getMaterialStockList();

      try {
        const response = await listPurchaseOrder(this.orderQueryParams);
        let list = response.rows;

        //采购订单数据筛选
        for (let i = 0; i < list.length; i++) {
          for (let j = 0; j < list[i].tblPurchaseOrderDetailList.length; j++) {
            let orderNum=list[i].tblPurchaseOrderDetailList[j].orderNum;
            let receiveNum=list[i].tblPurchaseOrderDetailList[j].receiveNum;
            let returnNum=list[i].tblPurchaseOrderDetailList[j].returnNum;

            if (orderNum > receiveNum && returnNum<(orderNum-receiveNum)){
              this.PurchaseOrderList.push(list[i]);
              break
            }
          }
        }

        //采购订单库存查询
        for (let i = 0; i < this.PurchaseOrderList.length; i++) {
          for (let j = 0; j < this.PurchaseOrderList[i].tblPurchaseOrderDetailList.length; j++) {
            if (this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].purchaseType==0){
              const stock = await this.getProductStock(
                this.PurchaseOrderList[i].scId,
                this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].productId
              );

              if (stock) {
                this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].baseDataProduct.tblProductStock = stock;
              } else {
                this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].baseDataProduct.tblProductStock = {
                  id: generateUniqueId(this.productStockAllList),
                  scId: this.PurchaseOrderList[i].scId,
                  productId: this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].productId,
                  stockNum: 0,
                  taxPrice: this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].taxPrice,
                  taxAmount: 0,
                };
              }
            }else {
              let num=this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].material.materialType
              let name= num==1 ? "原材料" : num==2 ? "半成品" :num==3 ? "成品" : "辅料"
              this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].material.typeName=name

              const stock = await this.getMaterialStock(
                this.PurchaseOrderList[i].scId,
                this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].materialId
              );

              if (stock) {
                this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].material.materialStock = stock;
              } else {
                this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].material.materialStock = {
                  id: generateUniqueId(this.materialStockAllList),
                  warehouseId: this.PurchaseOrderList[i].scId,
                  materialId: this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].materialId,
                  materialCode: this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].material.materialCode,
                  materialName: this.PurchaseOrderList[i].tblPurchaseOrderDetailList[j].material.materialName,
                  stockQuantity: 0,
                };
              }
            }
          }
        }
      } catch (error) {
        console.error('获取采购订单列表失败:', error);
      } finally {
        this.loading = false;
      }
    },


    handleRowClick(row, column, event) {
      this.selectedRowIndex = this.PurchaseOrderList.indexOf(row);
      this.selectedRowData = row; // 更新选中的行数据
    },
    handleRadioChange(index) {
      this.selectedRowIndex = index;
      // 清除其他行的选中状态
      this.$refs.singleTable.clearCurrentRow();
      this.$refs.singleTable.setCurrentRow(this.PurchaseOrderList[index]);
      this.selectedRowData = this.PurchaseOrderList[index]; // 更新选中的行数据
    },
    handleConfirm() {
      if (this.selectedRowData) {
        // 将选中的行数据传递给父组件
        this.$emit('order-selected', this.selectedRowData);
      }

      this.purchaseType=this.selectedRowData.tblPurchaseOrderDetailList[0].purchaseType

      this.orderId=this.selectedRowData.id;
      this.form.purchaseOrderId=this.selectedRowData.id
      this.form.scId=this.selectedRowData.scId
      this.form.supplierId=this.selectedRowData.supplierId
      this.form.purchaserId= parseInt(this.selectedRowData.purchaserId)
      this.form.purchaseOrderId=this.orderId

      this.tblReceiveSheetDetailList=[]
      for (let i = 0; i < this.selectedRowData.tblPurchaseOrderDetailList.length; i++) {
        var receiveSheet={}
        receiveSheet.id=generateUniqueId(this.ReceiveSheetDetailAllList)
        receiveSheet.sheetId=this.form.id
        if (this.selectedRowData.tblPurchaseOrderDetailList[i].purchaseType===0){
          receiveSheet.productId=this.selectedRowData.tblPurchaseOrderDetailList[i].productId
          receiveSheet.baseDataProduct=this.selectedRowData.tblPurchaseOrderDetailList[i].baseDataProduct;
        }else {
          receiveSheet.materialId=this.selectedRowData.tblPurchaseOrderDetailList[i].materialId
          receiveSheet.material=this.selectedRowData.tblPurchaseOrderDetailList[i].material;
        }
        receiveSheet.purchaseType=this.selectedRowData.tblPurchaseOrderDetailList[i].purchaseType
        receiveSheet.orderNum=this.selectedRowData.tblPurchaseOrderDetailList[i].orderNum
        receiveSheet.taxPrice=this.selectedRowData.tblPurchaseOrderDetailList[i].taxPrice
        receiveSheet.isGift=this.selectedRowData.tblPurchaseOrderDetailList[i].isGift
        receiveSheet.taxRate=this.selectedRowData.tblPurchaseOrderDetailList[i].taxRate
        receiveSheet.orderNo=i+1;
        receiveSheet.purchaseOrderDetailId=this.selectedRowData.tblPurchaseOrderDetailList[i].id
        receiveSheet.returnNum=0;

        receiveSheet.receiveNum=this.selectedRowData.tblPurchaseOrderDetailList[i].orderNum-this.selectedRowData.tblPurchaseOrderDetailList[i].receiveNum

        let detail=this.selectedRowData.tblPurchaseOrderDetailList[i];
        // let sum=0
        // for (let j = 0; j < this.ReceiveSheetList.length; j++) {
        //   for (let k = 0; k < this.ReceiveSheetList[j].tblReceiveSheetDetailList.length; k++) {
        //     let id=this.ReceiveSheetList[j].tblReceiveSheetDetailList[k].purchaseOrderDetailId
        //     let productId=this.ReceiveSheetList[j].tblReceiveSheetDetailList[k].productId
        //
        //     if (detail.id==id && detail.productId==productId){
        //       sum+=this.ReceiveSheetList[j].tblReceiveSheetDetailList[k].receiveNum
        //     }
        //   }
        // }
        // detail.remainderNum=detail.orderNum-sum

        receiveSheet.tblPurchaseOrderDetail=detail;
        this.tblReceiveSheetDetailList.push(receiveSheet);
      }

      // 初始化 sumPrice 属性
      this.tblReceiveSheetDetailList.forEach(row => {
        row.sumPrice = row.tblPurchaseOrderDetail.taxPrice * row.tblPurchaseOrderDetail.orderNum;
      });

      this.dialogFormVisible = false; // 关闭弹窗

      this.getSumNumber()
    },

    //商品库存
    async getProductStock(scId, productId) {
      try {
        const response = await listStock({ scId, productId });
        const stock = response.rows[0];
        return stock;
      }catch (error) {
        console.error('获取商品库存失败:', error);
        return null; // 返回 null 表示获取失败
      }
    },

    //物料库存
    async getMaterialStock(scId, materialId) {
      try {
        const response = await listMaterialStock({ warehouseId:scId, materialId:materialId });
        const stock = response.rows[0];
        return stock;
      }catch (error) {
        console.error('获取物料库存失败:', error);
        return null; // 返回 null 表示获取失败
      }
    },

    //商品库存
    async getProductStockList(){
      listStock().then(response => {
        this.productStockAllList=[]

        let list = response.rows;
        for (let i = 0; i < list.length; i++) {
          this.productStockAllList.push(list[i].id)
        }
      });
    },
    //物料库存
    async getMaterialStockList(){
      listMaterialStock().then(response => {
        this.materialStockAllList=[]

        let list = response.rows;
        for (let i = 0; i < list.length; i++) {
          this.materialStockAllList.push(list[i].id)
        }
      });
    },

    //计算总的收货数量、赠品数量、含税总金额
    getSumNumber(){
      const list=this.tblReceiveSheetDetailList;

      this.receiveNum=0;
      this.taxAmount=0;
      this.giftNum=0;
      this.orderNum=0;

      for (var i=0;i<list.length;i++){
        this.receiveNum+=Number(list[i].tblPurchaseOrderDetail.receiveNum);
        this.orderNum+=Number(list[i].tblPurchaseOrderDetail.orderNum);
        this.taxAmount+=list[i].tblPurchaseOrderDetail.taxPrice * list[i].tblPurchaseOrderDetail.orderNum;
      }

      this.form.totalAmount=this.taxAmount;
    },
    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.back();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        available: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      this.resetForm("form");
    },

    /** 提交按钮 */
    submitForm(status) {
      if(this.formInfo()){
        if (this.form.id != null) {

          //获取同一订单的不同收货单
          let list=[]
          for (let i = 0; i < this.ReceiveSheetList.length; i++) {
            if (this.ReceiveSheetList[i].purchaseOrderId==this.form.purchaseOrderId && this.ReceiveSheetList[i].id!=this.form.id){
              list.push(this.ReceiveSheetList[i])
            }
          }

          //修改采购订单详情已收货数量
          for (let i = 0; i < this.form.tblReceiveSheetDetailList.length; i++) {
            let detailId1=this.form.tblReceiveSheetDetailList[i].purchaseOrderDetailId;
            let productId1=this.form.tblReceiveSheetDetailList[i].productId;
            let sum=Number(this.form.tblReceiveSheetDetailList[i].receiveNum);

            for (let j = 0; j < list.length; j++) {
              for (let k = 0; k < list[j].tblReceiveSheetDetailList.length; k++) {
                let detailId2=list[j].tblReceiveSheetDetailList[k].purchaseOrderDetailId;
                let productId2=list[j].tblReceiveSheetDetailList[k].productId;
                if (detailId1==detailId2 && productId1==productId2){
                  sum+=Number(list[j].tblReceiveSheetDetailList[k].receiveNum);
                }
              }
            }

            this.form.tblReceiveSheetDetailList[i].tblPurchaseOrderDetail.receiveNum=sum;
          }

          updateReceiveSheet(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        } else {
          const newId = generateUniqueId(this.ReceiveSheetAllList);
          var code = getOrderCode(this.ReceiveSheetList);
          this.form.id=newId;
          this.form.code=code;
          for (var i = 0; i < this.tblReceiveSheetDetailList.length; i++) {
            this.tblReceiveSheetDetailList[i].sheetId=newId;
            this.tblReceiveSheetDetailList[i].tblPurchaseOrderDetail.receiveNum=Number(this.tblReceiveSheetDetailList[i].receiveNum)+Number(this.tblReceiveSheetDetailList[i].tblPurchaseOrderDetail.receiveNum);
          }
          this.form.tblReceiveSheetDetailList=this.tblReceiveSheetDetailList;
          this.form.createBy="系统管理员";
          this.form.createById="1";
          this.form.updateBy="系统管理员";
          this.form.updateById="1";
          this.form.totalNum=this.orderNum;
          this.form.totalGiftNum=this.giftNum;
          this.form.totalAmount=this.taxAmount;
          this.form.paymentDate = new Date();
          this.form.status=status;
          if (status==3 && this.formStatusInfo()){
            for (let i = 0; i < this.form.tblReceiveSheetDetailList.length; i++) {
              this.form.tblReceiveSheetDetailList[i].baseDataProduct.tblProductStock.stockNum+=this.form.tblReceiveSheetDetailList[i].orderNum
            }
            this.form.approveBy='1';
            this.form.approveTime=new Date();
          }

          addReceiveSheet(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        }
      }
    },
    //提交表单验证
    formInfo(){
      if (this.form.receiveDate==null){
        this.$modal.msgError("请选择到货日期");
        return false;
      }

      for (let i = 0; i < this.tblReceiveSheetDetailList.length; i++) {
        let receiveNum=Number(this.tblReceiveSheetDetailList[i].receiveNum);
        let returnNum=this.tblReceiveSheetDetailList[i].returnNum
        for (let j = 0; j < this.ReceiveSheetList.length; j++) {
          for (let k = 0; k < this.ReceiveSheetList[j].tblReceiveSheetDetailList.length; k++) {
            let detail=this.ReceiveSheetList[j].tblReceiveSheetDetailList[k];
            if (this.tblReceiveSheetDetailList[i].id!=detail.id){
              if (this.tblReceiveSheetDetailList[i].purchaseOrderDetailId==detail.purchaseOrderDetailId){
                receiveNum+=detail.receiveNum;
                returnNum+=detail.returnNum;
              }
            }
          }
        }

        if (this.tblReceiveSheetDetailList[i].tblPurchaseOrderDetail.returnNum>this.tblReceiveSheetDetailList[i].tblPurchaseOrderDetail.receiveNum){
          if (receiveNum>this.tblReceiveSheetDetailList[i].tblPurchaseOrderDetail.receiveNum){
            if (this.tblReceiveSheetDetailList[i].purchaseType==0){
              this.$modal.msgError(this.tblReceiveSheetDetailList[i].baseDataProduct.name+"的收货数量不能大于采购数量");
            }else {
              this.$modal.msgError(this.tblReceiveSheetDetailList[i].material.materialName+"的收货数量不能大于采购数量");
            }

            return false;
          }
        }else {
          if (receiveNum+this.tblReceiveSheetDetailList[i].tblPurchaseOrderDetail.returnNum>this.tblReceiveSheetDetailList[i].tblPurchaseOrderDetail.orderNum){
            if (this.tblReceiveSheetDetailList[i].purchaseType==0){
              this.$modal.msgError(this.tblReceiveSheetDetailList[i].baseDataProduct.name+"的收货数量不能大于采购数量");
            }else {
              this.$modal.msgError(this.tblReceiveSheetDetailList[i].material.materialName+"的收货数量不能大于采购数量");
            }

            return false;
          }
        }

      }

      return true;
    },

    //审核表单验证
    formStatusInfo(){
      for (var i = 0; i < this.tblReceiveSheetDetailList.length; i++) {
        if (this.tblReceiveSheetDetailList[i].tblPurchaseOrderDetail.receiveNum>this.tblReceiveSheetDetailList[i].tblPurchaseOrderDetail.orderNum){
          this.$modal.msgError(this.tblReceiveSheetDetailList[i].baseDataProduct.name+"的收货数量不能大于采购数量");
          return false;
        }
      }
      return true;
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/SettleInItem/export', {
        ...this.queryParams
      }, `SettleInItem_${new Date().getTime()}.xlsx`)
    },


    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },

    // 获取所有收货详情数据ID
    getReceiveSheetAllList(){
      this.orderIdList=[];
      this.ReceiveSheetList=[];
      this.ReceiveSheetAllList=[];
      this.ReceiveSheetDetailAllList=[];

      listReceiveSheet({}).then(response => {
          this.ReceiveSheetList=response.rows;

          for (var i=0;i<this.ReceiveSheetList.length;i++){
            this.ReceiveSheetAllList.push(this.ReceiveSheetList[i].id);
            this.orderIdList.push(this.ReceiveSheetList[i].purchaseOrderId)
            for (var j=0;j<this.ReceiveSheetList[i].tblReceiveSheetDetailList.length;j++){
              this.ReceiveSheetDetailAllList.push(this.ReceiveSheetList[i].tblReceiveSheetDetailList[j].id);
            }
          }
      });
    },
  },
  beforeRouteLeave(to, from, next) {
    // 设置一个标志，表示需要刷新数据
    to.meta.refresh = true;
    next();
  }
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}

//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="CGSH";    //采购收货
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>

